package com.zm.demo.netty.client.echo;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.net.InetSocketAddress;

/**
 * Created by Administrator on 2020/2/23.
 */
public class EchoClient {

    public static void main(String[]args) throws Exception{
//        for (int i = 0; i < 10; i++) {
            new EchoClient().start();
//        }
    }

    public void start() throws Exception{
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap();
            ChannelInitializer channelInitializer = new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel socketChannel) throws Exception {
                    socketChannel.pipeline().addLast(new EchoClientHandler());
                }
            };
            bootstrap.group(group)
                    .channel(NioSocketChannel.class)
                    .remoteAddress(new InetSocketAddress("127.0.0.1", 81))
                    .handler(channelInitializer);

            long start = System.currentTimeMillis();
            System.out.println("start  ====");
            for (int i = 0; i < 2000; i++) {
                ChannelFuture future = bootstrap.connect().sync();
                future.channel().closeFuture().sync();
            }
            System.out.println("end  ====, cost " + (System.currentTimeMillis() - start) + "ms");
        } catch (Exception e){
            e.printStackTrace();
        }finally {
            group.shutdownGracefully().sync();
        }
    }
}
